//
//  XYXEmoticonInputView.swift
//  表情键盘
//
//  Created by 亚杏 on 2017/6/12.
//  Copyright © 2017年 oms. All rights reserved.
//

import UIKit

//可重用标识符
private let cellID = "cellID"

class XYXEmoticonInputView: UIView {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var toolBar: XYXEmoticonToolBar!

    //分页控件
    @IBOutlet weak var pageControl: UIPageControl!
   

    //选中表情回调闭包属性
    var selectedEmoticonCallBack: ((_ emoticon:XYXEmoticonModel?) -> ())?

    // 加载并返回输入视图
    class func inputView(selectedEmoticon: @escaping (_ emoticon:XYXEmoticonModel?) -> ()) -> XYXEmoticonInputView {

        let nib = UINib(nibName: "XYXEmoticonInputView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! XYXEmoticonInputView
        //记录闭包
        v.selectedEmoticonCallBack = selectedEmoticon

        return v
    }



    override func awakeFromNib() {
        collectionView.backgroundColor = UIColor.white
        //注册可重用cell
        collectionView.register(XYXEmoticonCell.self, forCellWithReuseIdentifier: cellID)

        //设置工具栏代理 
        toolBar.delegate = self

        //设置分页控件的图片
        let bundle = XYXEmoticonManager.shared.bundle

        guard let normalImg = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil),
            let selectedImg = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else{
                return
        }

        //使用填充图片设置颜色 - 设置的图片变形
        //        pageControl.pageIndicatorTintColor = UIColor(patternImage: normalImg)
        //        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: selectedImg)

        // 使用 KVC 设置私有成员属性
        pageControl.setValue(normalImg, forKey: "_pageImage")
        pageControl.setValue(selectedImg, forKey: "_currentPageImage")

    }

}


extension XYXEmoticonInputView: XYXEmoticonToolBarDelegate {

    func emoticonToolbarDidSelectedItemIndex(toolbar: XYXEmoticonToolBar, index: Int) {

        //让 collectionView 发生滚动
        let indexPath = IndexPath(item: 0, section: index)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)

        //设置按钮的选中状态
        toolbar.selectedIndex = index

    }
}



extension XYXEmoticonInputView: UICollectionViewDataSource,XYXEmoticonCellDelegate {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return XYXEmoticonManager.shared.packages.count
    }

    //每个分组的表情包中，表情页面数量，即emoticons数组/20
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return XYXEmoticonManager.shared.packages[section].numberOfPages

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! XYXEmoticonCell
       //传递表情数组
        cell.emoticons = XYXEmoticonManager.shared.packages[indexPath.section].emoticon(page: indexPath.item)
        cell.delegate = self

        return cell
    }

    func emoticonCellDidSelectedEmoticon(cell: XYXEmoticonCell?, em: XYXEmoticonModel?) {
        //执行闭包
        selectedEmoticonCallBack?(em)

        //添加最近使用的表情
        guard let em = em else {
            return
        }

        //如果当前collectionView 就是最近的分组，不添加最近使用的表情
        let indexPath = collectionView.indexPathsForVisibleItems[0]
        if indexPath.section == 0 {
            return
        }

        //添加最近使用的表情
        XYXEmoticonManager.shared.recentEmoticon(em: em)

        //刷新数据
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView.reloadSections(indexSet)
    }

}


//MARK: UICollectionViewDelegate
extension XYXEmoticonInputView: UICollectionViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        //1.获取中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x

        //2.获取当前显示的 cell 的indexpath
        let indexpaths = collectionView.indexPathsForVisibleItems

        //3.判断中心点在哪一个indexPath上
        var targetIndexPath: IndexPath?

        for indexPath in indexpaths {

            //1.根据 indexPath 获得cell
            let cell = collectionView.cellForItem(at: indexPath)

            //2.判断中心点位置
            if cell?.frame.contains(center) == true {
                targetIndexPath = indexPath

                break
            }

        }

        guard let target = targetIndexPath else {
            return
        }

        //4.判断是否找到目标的 indexPath
        // indexPath.section -> 对应分组
        toolBar.selectedIndex = target.section

        //5.设置分页控件 
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item



    }
}
